﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Admin.NET.Core;
using Yitter.IdGenerator;

namespace Admin.NET.Application
{
    /// <summary>
    /// Pda半自动入库
    /// </summary>
    [ApiDescriptionSettings("Pda服务", Name = "AutomaticWarehouse", Order = 100)]
    [Route("api/[Controller]")]
    public class AutomaticWarehouseService : IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsOrder, MasterDbContextLocator> _wmsOrderRep;
        private readonly IRepository<WmsOrderDetails, MasterDbContextLocator> _wmsOrderDetailsRep;
        private readonly IRepository<WmsTask, MasterDbContextLocator> _wmsTaskRep;
        private readonly IRepository<WmsPlace, MasterDbContextLocator> _wmsPlaceRep;
        private readonly IRepository<WmsArea, MasterDbContextLocator> _wmsAreaRep;
        private readonly IRepository<WmsWarehouseEntrance, MasterDbContextLocator> _wmsWarehouseEntranceRep;
        private readonly IRepository<WmsMaterialContainer, MasterDbContextLocator> _wmsMaterialContainerRep;
        private readonly IRepository<WmsContainer, MasterDbContextLocator> _wmsContainerRep;
        private readonly IRepository<WmsContainerPlace, MasterDbContextLocator> _wmsContainerPlaceRep;
        private readonly IRepository<WmsMaterialStock, MasterDbContextLocator> _wmsMaterialStockRep;


        /// <summary>
        /// 构造函数
        /// </summary>
        public AutomaticWarehouseService(
            IRepository<WmsOrder, MasterDbContextLocator> wmsOrderRep,
            IRepository<WmsOrderDetails, MasterDbContextLocator> wmsOrderDetailsRep,
            IRepository<WmsTask, MasterDbContextLocator> wmsTaskRep,
            IRepository<WmsPlace, MasterDbContextLocator> wmsPlaceRep,
            IRepository<WmsArea, MasterDbContextLocator> wmsAreaRep,
            IRepository<WmsWarehouseEntrance, MasterDbContextLocator> wmsWarehouseEntranceRep,
            IRepository<WmsMaterialContainer, MasterDbContextLocator> wmsMaterialContainerRep,
            IRepository<WmsContainer, MasterDbContextLocator> wmsContainerRep,
            IRepository<WmsContainerPlace, MasterDbContextLocator> wmsContainerPlaceRep,
            IRepository<WmsMaterialStock, MasterDbContextLocator> wmsMaterialStockRep
        )
        {
            _wmsOrderRep = wmsOrderRep;
            _wmsOrderDetailsRep = wmsOrderDetailsRep;
            _wmsTaskRep = wmsTaskRep;
            _wmsPlaceRep = wmsPlaceRep;
            _wmsAreaRep = wmsAreaRep;
            _wmsWarehouseEntranceRep = wmsWarehouseEntranceRep;
            _wmsMaterialContainerRep = wmsMaterialContainerRep;
            _wmsContainerRep = wmsContainerRep;
            _wmsContainerPlaceRep = wmsContainerPlaceRep;
            _wmsMaterialStockRep = wmsMaterialStockRep;
        }

        ///// <summary>
        ///// 根据批次号获取明细
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpGet("GetDetail")]
        //public async Task<AutomaticWarehouseOutput> GetDetail([FromQuery] AutomaticWarehouseInput input)
        //{
        //    //根据号获取单据主表
        //    var wmsOrder =await _wmsOrderRep.DetachedEntities.FirstOrDefaultAsync(u => u.Batch == input.Batch
        //    && u.OrderDistributeType == TaskModel.BANZIDONG
        //    && u.OrderStatus == OrderStatusEnum.YIXIAFA
        //    );
        //    if (wmsOrder == null) throw Oops.Oh("单据被撤回或不存在!");
        //    //获取完成和执行中的最大的流水号的明细
        //    var modal = await _wmsOrderDetailsRep.DetachedEntities
        //        .Where(u => u.OrderId == wmsOrder.Id && (u.OrderStatus == OrderDetailsStatusEnum.ZHIXINGZHONG || u.OrderStatus == OrderDetailsStatusEnum.WANCHENG)
        //        ).OrderByDescending(u=>u.MaterialNo).FirstOrDefaultAsync();
        //    //不存在该类型的明细时返回最小的
        //    if (modal == null)
        //    {
        //        modal = await _wmsOrderDetailsRep.DetachedEntities
        //            .Where(u => u.OrderId == wmsOrder.Id && u.OrderStatus == OrderDetailsStatusEnum.WEIZHIXING)
        //            .OrderBy(u => u.MaterialNo).FirstOrDefaultAsync();
        //        if (modal == null) throw Oops.Oh("单据已完成!");
        //    }
        //    else {
        //        //返回流水号+1
        //        modal = await _wmsOrderDetailsRep.FirstOrDefaultAsync
        //            (u => u.MaterialNo == (Convert.ToInt32(modal.MaterialNo) + 1).ToString());
        //        if (modal == null)
        //        {
        //            modal = await _wmsOrderDetailsRep.DetachedEntities
        //            .Where(u => u.OrderId == wmsOrder.Id && u.OrderStatus == OrderDetailsStatusEnum.WEIZHIXING)
        //            .OrderBy(u => u.MaterialNo).FirstOrDefaultAsync();
        //            if (modal == null) throw Oops.Oh("单据已完成!");
        //        }
        //    }
            



        //    //没有下一个明细时根据单据主表获取单据明细中流水号最小并且未执行的
        //    //if (modal == null || Convert.ToDecimal(modal.MaterialNo.Substring(modal.MaterialNo.Length - 2)) == wmsOrder.OrderQuantityTotal)
        //    //{
        //    //    modal = await _wmsOrderDetailsRep.DetachedEntities
        //    //        .Where(u => u.OrderId == wmsOrder.Id && u.OrderStatus == OrderDetailsStatusEnum.WEIZHIXING)
        //    //        .OrderBy(u => u.MaterialNo).FirstOrDefaultAsync();
        //    //    if (modal == null) throw Oops.Oh("单据已完成!");
        //    //}
        //    //else
        //    //{
        //    //    //返回流水号+1
        //    //    modal = await _wmsOrderDetailsRep.FirstOrDefaultAsync
        //    //        (u => u.MaterialNo == (Convert.ToInt32(modal.MaterialNo) + 1).ToString());
        //    //    if (modal == null) throw Oops.Oh("单据已完成!");
        //    //}

        //    AutomaticWarehouseOutput output = new AutomaticWarehouseOutput();
        //    output.MaterialNo = modal.MaterialNo;
        //    output.Batch = modal.Batch;
        //    output.SerialNo = modal.MaterialNo.Substring(modal.MaterialNo.Length - 2);
        //    output.Long = modal.Long;
        //    output.Wide = modal.Wide;
        //    output.High = modal.High;
        //    output.PreferredPort = wmsOrder.PreferredPort;
        //    output.Id = wmsOrder.Id;
        //    return output;
        //}

        ///// <summary>
        ///// 获取入库口
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet("PdaGetWarehouseEntrance")]
        //public async Task<OutEntranceListDefaultCodeOutput> PdaGetWarehouseEntrance([FromQuery] PdaGetWarehouseEntranceInput input)
        //{
        //    OutEntranceListDefaultCodeOutput outEntranceListDefaultCodeOutput = new OutEntranceListDefaultCodeOutput();
        //    //根据单据id获取入库口
        //    var wmsOrder = await _wmsOrderRep.DetachedEntities.Where(x => x.Id == input.Id).ProjectToType<WmsOrder>().FirstOrDefaultAsync();
        //    List<WmsWarehouseEntrance> wmsWarehouseEntrance = new List<WmsWarehouseEntrance>();
        //    //根据，分割入库口字符串
        //    List<string> entranceList = new List<string>();
        //    if (wmsOrder.PreferredPort != null)
        //    {
        //        entranceList = wmsOrder.PreferredPort.Split(',').ToList();
        //    }
        //    //如果入库单选择多个库口则返回多个库口，单个则返回所有
        //    if (entranceList.Count>1)
        //    {
                
        //        foreach (var item in entranceList)
        //        {
        //          var wmsWarehouseEntranceModal = await _wmsWarehouseEntranceRep
        //          .FirstOrDefaultAsync(x => x.LesWorkShopType == LesWorkShopType.FAPAOCHEJIAN && x.Type == WarehouseEntranceEnum.RUKUKOU && x.Code == item);
        //          wmsWarehouseEntrance.Add(wmsWarehouseEntranceModal);
        //        }
        //        //获取上一条入库明细
        //        var lastWmsOrderDetailsModel = wmsOrder.WareOrderDetails
        //            .Where(z => z.OrderStatus == OrderDetailsStatusEnum.ZHIXINGZHONG || z.OrderStatus == OrderDetailsStatusEnum.WANCHENG).OrderByDescending(z => z.MaterialNo).FirstOrDefault();
        //        //如果不存在则默认赋值第一个
        //        if (lastWmsOrderDetailsModel == null)
        //        {
        //            //返回第一个
        //            outEntranceListDefaultCodeOutput.DefaultCode = entranceList[0];
        //        }
        //        else
        //        {
        //            //获取上一条入库任务
        //            var lastModel = await _wmsTaskRep.DetachedEntities
        //                    .FirstOrDefaultAsync(z => z.IsRead == false && z.OrderDetailsId == lastWmsOrderDetailsModel.Id);

        //            if (lastModel == null)
        //            {
        //                //返回第一个
        //                outEntranceListDefaultCodeOutput.DefaultCode = entranceList[0];
        //            }
        //            else
        //            {
        //                for (int i = 0; i < entranceList.Count; i++)
        //                {
        //                    if (lastModel.SourcePlace == entranceList[i])
        //                    {

        //                        if (i + 2 > entranceList.Count)
        //                        {
        //                            outEntranceListDefaultCodeOutput.DefaultCode = entranceList[0];
        //                        }
        //                        else
        //                        {
        //                            outEntranceListDefaultCodeOutput.DefaultCode = entranceList[i + 1];
        //                        }
        //                    }
        //                }
        //            }

        //        }
        //    }
        //    else
        //    {
        //         wmsWarehouseEntrance = await _wmsWarehouseEntranceRep
        //        .Where(x => x.LesWorkShopType == LesWorkShopType.FAPAOCHEJIAN && x.Type == WarehouseEntranceEnum.RUKUKOU).ToListAsync();
        //        outEntranceListDefaultCodeOutput.DefaultCode = entranceList[0];
        //    }
            
        //    List<OutEntranceListOutput> outEntranceListOutputLists = new List<OutEntranceListOutput>();
        //    foreach (var item in wmsWarehouseEntrance)
        //    {
        //        OutEntranceListOutput outEntranceListOutputList = new OutEntranceListOutput();
        //        outEntranceListOutputList.Code = item.Code;
        //        outEntranceListOutputList.Name = item.Name;
        //        outEntranceListOutputLists.Add(outEntranceListOutputList);
        //    }
        //    outEntranceListDefaultCodeOutput.OutEntranceListOutputList = outEntranceListOutputLists;
        //    return outEntranceListDefaultCodeOutput;
        //}

        public int GetAisle(string PreferredPort)
        {
            if (PreferredPort == "101")
            {
                return 1;
            }
            else if (PreferredPort == "102")
            {
                return 2;
            }
            else if (PreferredPort == "103")
            {
                return 3;
            }
            else if (PreferredPort == "104")
            {
                return 4;
            }
            else if (PreferredPort == "105")
            {
                return 5;
            }
            else if (PreferredPort == "106")
            {
                return 6;
            }
            else if (PreferredPort == "107")
            {
                return 7;
            }
            else if (PreferredPort == "108")
            {
                return 8;
            }
            else if (PreferredPort == "109")
            {
                return 9;
            }
            else if (PreferredPort == "110")
            {
                return 10;
            }
            else if (PreferredPort == "111")
            {
                return 11;
            }
            else
            {
                return 12;
            }

        }

        ///// <summary>
        ///// 提交入库
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost("PdaAutomaticWarehouse")]
        //[UnitOfWork]
        //public async Task PdaAutomaticWarehouse([FromBody] PdaAutomaticWarehouseInput input)
        //{

        //    var wmsOrderDetails = await _wmsOrderDetailsRep.FirstOrDefaultAsync(u => u.Batch == input.Batch && Convert.ToInt32(u.MaterialNo.Substring(u.MaterialNo.Length - 2)) == input.SerialNo && u.OrderStatus == OrderDetailsStatusEnum.WEIZHIXING);
        //    if (wmsOrderDetails == null) throw Oops.Oh("入库单明细不存在!");
        //    //验证主表单据是否为下发状态
        //    var wmsOrder = await _wmsOrderRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == wmsOrderDetails.OrderId);
        //    if (wmsOrder == null) throw Oops.Oh("单据被撤回或不存在!");
        //    //根据库口code获取库口信息
        //    var wmsWarehouseEntrance = await _wmsWarehouseEntranceRep.FirstOrDefaultAsync(u => u.Code == input.EntranceCode);
        //    if (wmsWarehouseEntrance == null) throw Oops.Oh("库口不存在!");
        //    //根据巷道获取空闲库位
        //    var wmsPlaceList = await _wmsPlaceRep.DetachedEntities.Where(x => x.AreaId == 416250842476613
        //    && x.Aisle == GetAisle(wmsWarehouseEntrance.Code)&&x.Islock == YesOrNot.N && x.PlaceStatus == PlaceStatus.KONGXIAN
        //    ).ToListAsync();
        //    if (wmsPlaceList.Count<=15) throw Oops.Oh("库位不足!");
        //    //更改明细表状态
        //    wmsOrderDetails.OrderStatus = OrderDetailsStatusEnum.ZHIXINGZHONG;
        //    await _wmsOrderDetailsRep.UpdateAsync(wmsOrderDetails);
        //    //应当判断同一入库口任务是否执行完成
        //    //判断上一条任务是否执行完(后期是否考虑堆垛机取货完成)
        //    var lastTask = await _wmsTaskRep.FirstOrDefaultAsync(u => u.Aisle == GetAisle(wmsWarehouseEntrance.Code)
        //    && u.TaskType == TaskType.RUKU && u.TaskStatus == TaskStatusEnum.ZHIXINGZHONG && (u.TaskDodeviceStatus == TaskDodeviceStatusEnum.ZX_RSSX || u.TaskDodeviceStatus == TaskDodeviceStatusEnum.W));
        //    if (lastTask != null) throw Oops.Oh("上条任务未完成,请稍后操作!");
        //    var wmsContainer = new WmsContainer();
        //    //矫正数据异常
        //    while (true)
        //    {
        //        //获取托盘,实际上没有托盘
        //        wmsContainer = await _wmsContainerRep.FirstOrDefaultAsync(u => u.WorkShopType == LesWorkShopType.FAPAOCHEJIAN && u.ContainerStatus == ContainerStatus.KOUXIAN && u.IsVirtually == YesOrNot.Y);
        //        if (wmsContainer == null) throw Oops.Oh("无虚拟托盘!");
        //        var materialStock = await _wmsMaterialStockRep.Where(p => p.ContainerCode == wmsContainer.ContainerCode).FirstOrDefaultAsync();
        //        if (materialStock == null) {
        //            wmsContainer.ContainerStatus = ContainerStatus.ZUPANG;
        //            await _wmsContainerRep.UpdateNowAsync(wmsContainer);
        //            break;
        //        }
        //        else
        //        {
        //            wmsContainer.ContainerStatus = ContainerStatus.KUWEI;
        //            await _wmsContainerRep.UpdateNowAsync(wmsContainer);
        //        };
        //    }
        //    //创建组盘记录
        //    WmsMaterialContainer bindentranceModel = new WmsMaterialContainer();
        //    bindentranceModel.ContainerId = wmsContainer.Id;
        //    bindentranceModel.ContainerCode = wmsContainer.ContainerCode;
        //    bindentranceModel.MaterialNo = wmsOrderDetails.MaterialNo;
        //    bindentranceModel.MaterialBatch = wmsOrderDetails.Batch;
        //    bindentranceModel.BindQuantity = 1;
        //    bindentranceModel.OrderDetailsId = wmsOrderDetails.Id;
        //    bindentranceModel.MaterialDensity = wmsOrderDetails.MaterialDensity;
        //    bindentranceModel.BindStatus = CommonStatus.ENABLE;
        //    bindentranceModel.OrderNo = wmsOrder.OrderNo;
        //    bindentranceModel.MaterialName = "N/A";
        //    await _wmsMaterialContainerRep.InsertAsync(bindentranceModel);
            
        //    //根据明细id获取任务
        //    var wmsTask = await _wmsTaskRep.FirstOrDefaultAsync(u => u.OrderDetailsId == wmsOrderDetails.Id);
        //    if (wmsTask == null) throw Oops.Oh("该任务不存在!");

        //    //更改任务
        //    wmsTask.OrderNo = bindentranceModel.OrderNo;
        //    wmsTask.TaskLevel = 2;
        //    wmsTask.ContainerCode = wmsContainer.ContainerCode;
        //    wmsTask.SourcePlace = wmsWarehouseEntrance.Code;//入库口
        //    wmsTask.Aisle = GetAisle(wmsWarehouseEntrance.Code);
        //    wmsTask.TaskStatus = TaskStatusEnum.ZHIXINGZHONG;
        //    wmsTask.IsRead = true;//wcs是否可以读取
        //    wmsTask.TaskDodeviceStatus = TaskDodeviceStatusEnum.W;
        //    await _wmsTaskRep.UpdateAsync(wmsTask);
        //}
    }
}
